package com.threeonemeeting.activity;

import java.util.ArrayList;
import java.util.Map;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnDoubleTapListener;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.snda.lib.http.HttpUtil;
import com.snda.lib.http.ICallBack;
import com.snda.lib.http.TaskManager;
import com.snda.lib.util.ImageDownloader;
import com.snda.lib.util.ImageHelper;
import com.threeonemeeting.Const;
import com.threeonemeeting.R;
import com.threeonemeeting.adapter.IconItemListAdapter;
import com.threeonemeeting.list.BannerAdvInfoList;
import com.threeonemeeting.model.BannerAdvInfo;
import com.threeonemeeting.model.IconItemInfo;
import com.threeonemeeting.model.ScreenInfo;
import com.threeonemeeting.tab.BaseTabActivity;
import com.threeonemeeting.task.GetBannerAdvTask;
import com.threeonemeeting.task.HttpConst;
import com.threeonemeeting.util.AppSettings;

public class MainHomeActivity extends BaseTabActivity implements ICallBack,
		OnItemClickListener, OnGestureListener, OnDoubleTapListener,
		OnTouchListener {

	public static final int FLIP_MSG = 1; // ViewFlipper的切换消息
	public static final int FLIP_INTERNAL = Const.Times.SECOND * 6; // ViewFlipper的切换消息

	private ListView listNav = null;
	private ViewFlipper mViewFlipper = null;
	private GestureDetector mGestureDetector;

	private ArrayList<IconItemInfo> mIconListItem;
	private IconItemListAdapter mIconListItemAdapter;

	// Banner adv相关
	private BannerAdvInfoList mBannerList = null;

	// 通过Handler进行UI的更新
	Handler uiHandler = new Handler() {
		public void handleMessage(Message msg) {
			mIconListItemAdapter.notifyDataSetChanged();
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ac_home);
		mGestureDetector = new GestureDetector(this);

		mViewFlipper = (ViewFlipper) findViewById(R.id.vf_flipper);
		mViewFlipper.setOnTouchListener(this);
		mViewFlipper.setLongClickable(true);

		int nWidth = ScreenInfo.getInstance(this).getHorizontalSize();

		LinearLayout flipperLayout = (LinearLayout) findViewById(R.id.flipperLayout);
		flipperLayout.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.FILL_PARENT, nWidth / 2));

		listNav = (ListView) findViewById(R.id.navList);
		mIconListItem = new ArrayList<IconItemInfo>();

		IconItemInfo info = new IconItemInfo();
		info = new IconItemInfo();
		info.nIconResId = R.drawable.hot;
		info.strText = "热门会议";
		mIconListItem.add(info);

		info = new IconItemInfo();
		info.nIconResId = R.drawable.channel;
		info.strText = "行业频道";
		mIconListItem.add(info);

		info = new IconItemInfo();
		info.nIconResId = R.drawable.browser;
		info.strText = "随便看看";
		mIconListItem.add(info);

		info = new IconItemInfo();
		info.nIconResId = R.drawable.express;
		info.strText = "附近的会议";
		mIconListItem.add(info);

		mIconListItemAdapter = new IconItemListAdapter(this,
				R.layout.lvi_home_icon_item);
		mIconListItemAdapter.setIconList(mIconListItem);
		listNav.setAdapter(mIconListItemAdapter);
		listNav.setOnItemClickListener(this);

		// 发送请求请求首页的Banner广告
		GetBannerAdvTask task = new GetBannerAdvTask(this, this);
		TaskManager.addTask(task, null, true);

		final EditText editSearch = (EditText) findViewById(R.id.editSearch);
		editSearch.setOnFocusChangeListener(new OnFocusChangeListener() {

			public void onFocusChange(View v, boolean hasFocus) {
				String strHint = getResources().getString(
						R.string.string_search_meeting);
				String strSearch = editSearch.getText().toString();
				if (hasFocus == true) {
					if (strSearch.equalsIgnoreCase(strHint) == true) {
						editSearch.setText("");
					}
				} else {

					if (strSearch.equalsIgnoreCase("") == true) {
						editSearch.setText(strHint);
					}
				}
			}
		});

		// 搜索按钮
		Button btnSearch = (Button) findViewById(R.id.btn_search);
		OnClickListener searchBtnClickListener = new OnClickListener() {

			public void onClick(View v) {
				if (editSearch.getText().toString().equalsIgnoreCase("") == true) {
					return;
				}

				if (editSearch
						.getText()
						.toString()
						.equalsIgnoreCase(
								MainHomeActivity.this.getResources().getString(
										R.string.string_search_meeting)) == true) {
					return;
				}

				Bundle b = new Bundle();
				b.putString("keyword", editSearch.getText().toString());
				b.putString("title", "搜索：" + editSearch.getText().toString());
				startActivity("SearchMeetingListActivity", b);
			}
		};
		if (btnSearch != null) {
			btnSearch.setOnClickListener(searchBtnClickListener);
		}

		showLoadingLayout(true);

		final LinearLayout navListLayout = (LinearLayout) findViewById(R.id.navListLayout);
		ViewTreeObserver obs = navListLayout.getViewTreeObserver();
		obs.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
			public boolean onPreDraw() {

				int nHeight = navListLayout.getHeight();

				mIconListItemAdapter.setMinHeight(nHeight / 4);
				uiHandler.sendEmptyMessage(0);

				return true;
			}
		});
	}

	@Override
	public void onStop() {
		super.onStop();

		mViewFlipper.stopFlipping();
	}

	class BannerImageLoadedCallback implements ImageDownloader.Callback {

		public BannerAdvInfo bannerAdvInfo = null;

		public BannerImageLoadedCallback() {
		}

		public void imageLoaded(Bitmap bm, String strImageUrl) {
			if (mViewFlipper == null)
				return;

			// 加入到ViewFlipper中
			LinearLayout imageLayout = new LinearLayout(MainHomeActivity.this);
			LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
					LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
			mViewFlipper.addView(imageLayout, lp);

			ImageView imageView = new ImageView(MainHomeActivity.this);
			imageView.setScaleType(ScaleType.FIT_XY);
			imageView.setBackgroundDrawable(ImageHelper.bitmap2Drawable(bm));
			imageLayout.addView(imageView, lp);

			if (bannerAdvInfo != null) {
				bannerAdvInfo.flippingView = imageLayout;
			}

			if (mViewFlipper.isFlipping() == false) {

				showLoadingLayout(false);

				mViewFlipper.setFlipInterval(Const.Times.SECOND * 10);
				mViewFlipper.startFlipping();
			}

		}
	}

	public void doCallBack(Map<String, Object> map) {
		Integer msgType = (Integer) map.get(HttpConst.KEY_TASK_TYPE);
		if (msgType == null) {
			Log.d(Const.Tag, "can't find type in response type");
			return;
		}

		Integer nError = (Integer) map.get(HttpUtil.KEY_ERROR_CODE);
		if (nError == null || nError != HttpUtil.ERROR_SUCCESS) {
			Log.d(Const.Tag, "response return error:" + nError + " type:"
					+ msgType);
			return;
		}

		// 获取轮播广告成功
		if (msgType == HttpConst.TASKTYPE_GETBANNER) {

			mBannerList = (BannerAdvInfoList) map.get(Const.Keys.KEY_LIST);
			if (mBannerList == null)
				return;

			for (int i = 0; i < mBannerList.size(); i++) {
				BannerAdvInfo bannerInfo = mBannerList.get(i);
				if (bannerInfo == null)
					continue;

				if (bannerInfo.bUsing == false)
					continue;

				// 获取图片
				String strImageUrl = bannerInfo.strImageUrl;
				BannerImageLoadedCallback wrapCallback = new BannerImageLoadedCallback();
				Bitmap bm = ImageDownloader.loadImage(getApplicationContext(),
						strImageUrl,
						AppSettings.getImagePath(getApplicationContext()),
						wrapCallback);
				if (bm != null) {
					wrapCallback.bannerAdvInfo = bannerInfo;
					wrapCallback.imageLoaded(bm, strImageUrl);
				}
			}
		}

	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (arg0 == listNav) {

			// 热门会议
			if (arg2 == 0) {
				startActivity("HotMeetingListActivity");
			}
			// 行业频道
			else if (arg2 == 1) {
				Intent bIntent = new Intent(Const.Broadcast.ACTION_CHANGE_TAB);
				bIntent.putExtra(Const.Broadcast.CURRENT_TAB_INDEX, 1);
				sendBroadcast(bIntent);
			}
			// 随便看看
			else if (arg2 == 2) {
				Bundle b = new Bundle();
				b.putString("keyword", "");
				b.putString("title", "全部行业");
				startActivity("SearchMeetingListActivity", b);

			} else if (arg2 == 3) {
				startActivity("NearByMeetingListActivity");
			}
		}
	}

	private void showLoadingLayout(boolean bShow) {
		LinearLayout loadingLayout = (LinearLayout) findViewById(R.id.layout_loading);
		TextView loadingText = (TextView) findViewById(R.id.loading_text);

		if (bShow == true) {
			loadingLayout.setVisibility(View.VISIBLE);
			loadingText.setText("正在加载图片...");
			mViewFlipper.setVisibility(View.GONE);
		} else {
			loadingLayout.setVisibility(View.GONE);
			mViewFlipper.setVisibility(View.VISIBLE);
		}
	}

	public boolean onDoubleTap(MotionEvent e) {
		if (mViewFlipper.isFlipping()) {
			mViewFlipper.stopFlipping();
		} else {
			mViewFlipper.startFlipping();
		}
		return true;
	}

	public boolean onDoubleTapEvent(MotionEvent e) {
		return false;
	}

	public boolean onSingleTapConfirmed(MotionEvent e) {
		return false;
	}

	public boolean onDown(MotionEvent e) {
		LinearLayout clickedLayout = (LinearLayout) mViewFlipper
				.getCurrentView();

		BannerAdvInfo bannerInfo = mBannerList.getBannerInfo(clickedLayout);
		if (bannerInfo == null)
			return false;

		if (bannerInfo.nEventId != 0) {

			// 跳转到会议详情页面
			Bundle b = new Bundle();
			b.putInt("id", bannerInfo.nEventId);
			startActivity("MeetingDetailActivity", b);
		}

		// 打开网页
		else if (TextUtils.isEmpty(bannerInfo.strImageUrl) == false) {
			// 跳转到会议详情页面
			Bundle b = new Bundle();
			b.putString("url", bannerInfo.strLinkUrl);
			startActivity("MeetingWebViewActivity", b);

		}

		return false;
	}

	/**
	 * 
	 * 定义从右侧进入的动画效果
	 * 
	 * @return
	 */
	protected Animation inFromRightAnimation() {
		Animation inFromRight = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, +1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		inFromRight.setDuration(250);
		inFromRight.setInterpolator(new AccelerateInterpolator());
		return inFromRight;
	}

	/**
	 * 
	 * 定义从左侧退出的动画效果
	 * 
	 * @return
	 */
	protected Animation outToLeftAnimation() {
		Animation outtoLeft = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, -1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		outtoLeft.setDuration(250);
		outtoLeft.setInterpolator(new AccelerateInterpolator());
		return outtoLeft;
	}

	/**
	 * 
	 * 定义从左侧进入的动画效果
	 * 
	 * @return
	 */
	protected Animation inFromLeftAnimation() {
		Animation inFromLeft = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, -1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		inFromLeft.setDuration(250);
		inFromLeft.setInterpolator(new AccelerateInterpolator());
		return inFromLeft;
	}

	/**
	 * 
	 * 定义从右侧退出时的动画效果
	 * 
	 * @return
	 */
	protected Animation outToRightAnimation() {
		Animation outtoRight = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, +1.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f);
		outtoRight.setDuration(250);
		outtoRight.setInterpolator(new AccelerateInterpolator());
		return outtoRight;
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e1.getX() > e2.getX() + 10 && Math.abs(velocityX) > 10) { // 向左划超过10px
			mViewFlipper.setInAnimation(getApplicationContext(),
					R.anim.push_left_in);
			mViewFlipper.setOutAnimation(getApplicationContext(),
					R.anim.push_left_out);
			mViewFlipper.showNext();
		} else if (e1.getX() < e2.getX() + 10) { // 向右划超过10px
			mViewFlipper.setInAnimation(getApplicationContext(),
					R.anim.push_left_in);
			mViewFlipper.setOutAnimation(getApplicationContext(),
					R.anim.push_left_out);
			mViewFlipper.showPrevious();
		}

		return false;
	}

	public void onLongPress(MotionEvent e) {
	}

	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return false;
	}

	public void onShowPress(MotionEvent e) {
	}

	public boolean onSingleTapUp(MotionEvent e) {
		return false;
	}

	public boolean onTouch(View v, MotionEvent event) {

		// 一定要将触屏事件交给手势识别类去处理（自己处理会很麻烦的）
		return mGestureDetector.onTouchEvent(event);
	}

}
